package com.felix.apigw;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class ConfigJsonParser {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Configuration configuration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider(objectMapper))
            .mappingProvider(new JacksonMappingProvider(objectMapper))
            .build();

    public static String getConfig(String json) {
        DocumentContext documentContext = JsonPath.using(configuration).parse(json);
        // 直接复制接口里面的json
        ArrayNode read = documentContext.read("$[*].route_definition", ArrayNode.class);
        String configInfo;
        if (!read.isEmpty()) {
            configInfo = read.toPrettyString();
        } else {
            configInfo = documentContext.jsonString();
        }
        return configInfo;
    }

    public static String getConfig(File file) throws IOException {
        String fileString = FileUtils.readFileToString(file);
        return getConfig(fileString);
    }
}
